package cn.ug.operation.service.impl;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.enums.SharePrizeTypeEnum;
import cn.ug.operation.bean.SharePrizeBean;
import cn.ug.operation.bean.SharePrizeSettingBean;
import cn.ug.operation.mapper.SharePrizeMapper;
import cn.ug.operation.mapper.entity.SharePrizeEntity;
import cn.ug.operation.mapper.entity.ShareUserTypeSetting;
import cn.ug.operation.service.SharePrizeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SharePrizeServiceImpl implements SharePrizeService {

    @Resource
    private SharePrizeMapper sharePrizeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String CUSTOM_KEY = "customKey";
    @Override
    public SerializeObject save(List<SharePrizeBean> sharePrizeBeanList) {
        if (!CollectionUtils.isEmpty(sharePrizeBeanList)){
            Map<Integer, List<SharePrizeBean>> resultList = sharePrizeBeanList.stream().collect(Collectors.groupingBy(SharePrizeBean::getGroupId));
            for (Map.Entry<Integer, List<SharePrizeBean>> entry : resultList.entrySet()) {
                List<SharePrizeBean> sharePrizeBeans = entry.getValue();
                if(CollectionUtils.isEmpty(sharePrizeBeans)){
                    return new SerializeObjectError("25000087");
                }

                BigDecimal sum = sharePrizeBeans.stream().map(SharePrizeBean::getProbability).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (sum.intValue() != 100){
                    return new SerializeObjectError("25000083");
                }
                //判断添加的奖品中有没有重复的奖品 当前获取集合中所以的奖品类型（尚未去重）
                List<Integer> types = sharePrizeBeans.stream().map(o->o.getType()).collect(Collectors.toList());
                //针对集合中的类型进行去重
                Long count = types.stream().distinct().count();
                if (types.size()!=count.intValue()){
                    return new SerializeObjectError("25000084");
                }
            }

            for (SharePrizeBean sharePrizeBean : sharePrizeBeanList){
                if (sharePrizeBean.getGroupType() == null || sharePrizeBean.getGroupId() == null) {
                    return new SerializeObjectError("25000074");
                }

                if ((SharePrizeTypeEnum.CASH.getType() == sharePrizeBean.getType() ||
                        SharePrizeTypeEnum.EXPERIENCE_GOLD.getType() == sharePrizeBean.getType() ||
                        SharePrizeTypeEnum.GOLD_BEAN.getType() == sharePrizeBean.getType()) &&  sharePrizeBean.getAmount()==null){
                    return new SerializeObjectError("25000085");
                }

                if ((SharePrizeTypeEnum.KICKBACK.getType() == sharePrizeBean.getType() ||
                        SharePrizeTypeEnum.INTEREST.getType() == sharePrizeBean.getType() ||
                        SharePrizeTypeEnum.SHOP_ELECTRONIC_CARD.getType() == sharePrizeBean.getType()) && StringUtils.isBlank(sharePrizeBean.getCouponIds())){
                    return new SerializeObjectError("25000086");
                }
                SharePrizeEntity sharePrizeEntity = new SharePrizeEntity();
                //修改
                if (sharePrizeBean.getId() != null) {
                    update(sharePrizeBean);
                } else {
                    //新增
                    BeanUtils.copyProperties(sharePrizeBean, sharePrizeEntity);
                    sharePrizeEntity.setQuantityLimit(0);
                    sharePrizeEntity.setDeleted(1);
                    int rows = sharePrizeMapper.insert(sharePrizeEntity);
                    Ensure.that(rows).isLt(1, "00000005");
                }
            }
            redisTemplate.delete(CUSTOM_KEY);
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject queryList() {
        List<ShareUserTypeSetting> shareUserTypeSettingList = sharePrizeMapper.queryGroup();
        String customKeyIds = redisTemplate.opsForValue().get(CUSTOM_KEY);
        if (StringUtils.isNotBlank(customKeyIds)){
            String[] customKey = customKeyIds.split(",");
            for (String id : customKey){
                if (StringUtils.isNotBlank(id)){
                    ShareUserTypeSetting settingBean = new ShareUserTypeSetting();
                    settingBean.setGroupId(Integer.valueOf(id));
                    settingBean.setGroupType(4);
                    shareUserTypeSettingList.add(settingBean);
                }
            }
        }

        if (!CollectionUtils.isEmpty(shareUserTypeSettingList)) {
            List<SharePrizeSettingBean> sharePrizeSettingBeans = new ArrayList<>();
            for (ShareUserTypeSetting shareUserTypeSetting : shareUserTypeSettingList) {
                SharePrizeSettingBean sharePrizeSettingBean = new SharePrizeSettingBean();
                BeanUtils.copyProperties(shareUserTypeSetting, sharePrizeSettingBean);
                List<SharePrizeEntity> sharePrizeEntityList = sharePrizeMapper.queryListByGroupId(shareUserTypeSetting.getGroupId());
                if (!CollectionUtils.isEmpty(sharePrizeEntityList)) {
                    List<SharePrizeBean> sharePrizeBeanList = new ArrayList<>();
                    for (SharePrizeEntity sharePrizeEntity : sharePrizeEntityList) {
                        SharePrizeBean sharePrizeBean = new SharePrizeBean();
                        BeanUtils.copyProperties(sharePrizeEntity, sharePrizeBean);
                        sharePrizeBeanList.add(sharePrizeBean);
                    }
                    sharePrizeSettingBean.setSharePrizeBeans(sharePrizeBeanList);
                }
                sharePrizeSettingBeans.add(sharePrizeSettingBean);
            }
            return new SerializeObject<>(ResultType.NORMAL, sharePrizeSettingBeans);
        }
        return null;
    }

    @Override
    public SerializeObject update(SharePrizeBean sharePrizeBean) {
        if (sharePrizeBean.getId() == null) {
            return new SerializeObjectError("00000003");
        }
        SharePrizeEntity sharePrizeEntity = sharePrizeMapper.queryById(sharePrizeBean.getId());
        if (sharePrizeEntity == null) {
            return new SerializeObjectError("00000003");
        }
        Map requestMap = new HashMap();
        requestMap.put("name", sharePrizeBean.getName());
        requestMap.put("type", sharePrizeBean.getType());
        requestMap.put("amount", sharePrizeBean.getAmount());
        requestMap.put("quantityLimit", sharePrizeBean.getQuantityLimit());
        requestMap.put("quantity", sharePrizeBean.getQuantity());
        requestMap.put("couponIds", sharePrizeBean.getCouponIds());
        requestMap.put("probability", sharePrizeBean.getProbability());
        requestMap.put("id", sharePrizeBean.getId());
        int rows = sharePrizeMapper.update(requestMap);
        Ensure.that(rows).isLt(1, "00000005");
        return new SerializeObject<>(ResultType.NORMAL, "00000001");

    }

    /**
     * 删除
     *
     * @param id   商品id/用户组id
     * @param type 1.商品  2.用户组
     * @return
     */
    @Override
    public SerializeObject delete(Integer id, Integer type) {
        if (type == 1) {
            SharePrizeEntity sharePrizeEntity = sharePrizeMapper.queryById(id);
            if (sharePrizeEntity == null) {
                return new SerializeObjectError("00000003");
            }
            //自定义用户群
            if (sharePrizeEntity.getGroupType() == 4){
                List<SharePrizeEntity> prizeEntityList = sharePrizeMapper.queryListByGroupId(sharePrizeEntity.getGroupId());
                if(!CollectionUtils.isEmpty(prizeEntityList) && prizeEntityList.size()==1 && prizeEntityList.get(0).getId().intValue() == id.intValue()){
                    String customKeyId = redisTemplate.opsForValue().get(CUSTOM_KEY);
                    if(StringUtils.isNotBlank(customKeyId)){
                        redisTemplate.opsForValue().set(CUSTOM_KEY,customKeyId+","+sharePrizeEntity.getGroupId());
                    }else {
                        redisTemplate.opsForValue().set(CUSTOM_KEY,","+sharePrizeEntity.getGroupId().toString());
                    }
                }
            }
            int rows = sharePrizeMapper.delete(id);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        } else {
            String customKeyIds = redisTemplate.opsForValue().get(CUSTOM_KEY);
            if (StringUtils.isNotBlank(customKeyIds) && customKeyIds.contains(id.toString())){
                //redisTemplate.delete(CUSTOM_KEY+id);
                 customKeyIds = customKeyIds.replaceAll(","+id,"");

                redisTemplate.opsForValue().set(CUSTOM_KEY,customKeyIds);
                return new SerializeObject<>(ResultType.NORMAL, "00000001");
            }

            List<SharePrizeEntity> result = sharePrizeMapper.queryListByGroupId(id);
            if(CollectionUtils.isEmpty(result)){
                return new SerializeObject(504,"没有该群组id");
            }
            List<SharePrizeEntity> sharePrizeEntityList = sharePrizeMapper.queryByType(4);
            if(!CollectionUtils.isEmpty(sharePrizeEntityList) && sharePrizeEntityList.size()==1){
                return new SerializeObjectError("25000081");
            }
            Map requestMap = new HashMap();
            requestMap.put("deleted", 2);
            requestMap.put("groupId", id);
            int rows = sharePrizeMapper.update(requestMap);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
    }


}
